package shapewar.net.io;

import java.io.UnsupportedEncodingException;

public class Tool {
	private static byte[] intToBytes(int value[]) {
	    byte[] bytes = new byte[4 * (value.length+1)];
	    bytes[0] = (byte) value.length;
	    for(int i=0;i<value.length;i++){
	    	bytes[(4 * (i + 1))+3] = (byte) ((value[i] & 0xFF000000)>>24);  
	    	bytes[(4 * (i + 1))+2] = (byte) ((value[i] & 0x00FF0000)>>16);  
	    	bytes[(4 * (i + 1))+1] = (byte) ((value[i] & 0x0000FF00)>>8);    
	    	bytes[(4 * (i + 1))+0] = (byte) ((value[i] & 0x000000FF));
	    }
	    return bytes;
	}
	
	private static int [] bytesToInts(byte[] ary,int offset,int len) {  
	    int value[] = new int[len/4];
	    for(int i=offset/4;i<offset/4+len/4;i++){
		    value[i-offset/4] = (int) ((ary[i*4+0] & 0xFF)   
		            | ((ary[i*4+1]<<8) & 0xFF00)  
		            | ((ary[i*4+2]<<16) & 0xFF0000)   
		            | ((ary[i*4+3]<<24) & 0xFF000000));  
	    }
	    return value;
	    
	}
	
	private static int [] bytesToInts(byte[] ary) {  
		return bytesToInts(ary,4,ary[0]*4);
	}
	
	public static byte[] combine(int[] ary,String str) throws UnsupportedEncodingException{
		byte b1[] = new byte[0];
		byte b2[] = new byte[0];
		if(ary!=null){
			b1 = intToBytes(ary);
		}
		if(str!=null){
			b2 = str.getBytes("UTF-8");
		}
		byte b3[] = new byte[b1.length + b2.length];
		for(int i=0;i<b3.length;i++){
			b3[i] = i<b1.length?b1[i]:b2[i-b1.length];
		}
		b3[2] = (byte) b2.length;
		return b3;
	}
	
	public static int[] depart(byte[] b){
		return bytesToInts(b);
	}
	
	public static String departs(byte[] b) throws UnsupportedEncodingException{
		return new String(b,(b[0]+1) * 4,b[2],"UTF-8");
	}
}
